/**
 * 图片转base64
 * @param {*} files e.target.files[0]
 */
export function imgToBase64(files) {
	return new Promise((resolve, reject) => {
		const afterFiles = {
			file: files,
		};
		const reader = new FileReader();
		reader.readAsDataURL(files);

		reader.onload = function () {
			afterFiles.content = this.result;
			resolve(afterFiles);
			// return afterFiles;
		};
		reader.onerror = function () {
			console.error('图片转换base64失败');
			reject({
				code: -1,
				msg: '图片转换base64失败',
			});
		};
	});
}

/**
 * base64转图片
 * @param {*} dataurl base64
 * @param {*} filename 转换后File名称
 * @returns
 */
export function dataURLtoFile(dataurl, filename = 'file') {
	let arr = dataurl.split(',');
	let mime = arr[0].match(/:(.*?);/)[1];
	let suffix = mime.split('/')[1];
	let bstr = window.atob(arr[1]);
	let n = bstr.length;
	let u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new File([u8arr], `${filename}.${suffix}`, {
		type: mime,
	});
}
